package com.ruoyi.system.service.impl.smy;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.constant.UserType;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.smy.Distributor;
import com.ruoyi.common.core.domain.smy.MallMerchantPersonalInfo;
import com.ruoyi.common.core.domain.smy.SecurityWebUser;
import com.ruoyi.system.mapper.smy.SecurityWebUserMapper;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.smy.IDistributorService;
import com.ruoyi.system.service.smy.IMallMerchantPersonalInfoService;
import com.ruoyi.system.service.smy.ISecurityWebUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class SecurityWebUserServiceImpl implements ISecurityWebUserService {

	@Resource
	private SecurityWebUserMapper securityWebUserMapper;

	@Resource
	private IMallMerchantPersonalInfoService personalInfoService;

	@Resource
	private IDistributorService distributorService;

	@Resource
	private ISysRoleService roleService;

	@Override
	public SecurityWebUser selectSecurityWebUserById(Long id) {
		return securityWebUserMapper.selectSecurityWebUserById(id);
	}

	@Override
	public List<SecurityWebUser> selectSecurityWebUserList(SecurityWebUser securityWebUser) {
		return securityWebUserMapper.selectSecurityWebUserList(securityWebUser);
	}

	@Override
	public int insertSecurityWebUser(SecurityWebUser securityWebUser) {
		return securityWebUserMapper.insertSecurityWebUser(securityWebUser);
	}

	@Override
	public int updateSecurityWebUser(SecurityWebUser securityWebUser) {
		if(StrUtil.isNotEmpty(securityWebUser.getGroupType())){
			MallMerchantPersonalInfo personalInfo = personalInfoService.selectMallMerchantPersonalInfoById(securityWebUser.getMerchantpersonalinfoId());
			if(Objects.nonNull(personalInfo)){
				personalInfo.setGrouptype(securityWebUser.getGroupType());
				personalInfoService.updateMallMerchantPersonalInfo(personalInfo);
			}
		}
		return securityWebUserMapper.updateSecurityWebUser(securityWebUser);
	}

	@Override
	public int deleteSecurityWebUserByIds(Long[] ids) {
		return securityWebUserMapper.deleteSecurityWebUserByIds(ids);
	}

	@Override
	public int deleteSecurityWebUserById(Long id) {
		return securityWebUserMapper.deleteSecurityWebUserById(id);
	}

	@Override
	public void changeMerchantStatus(String optId, String optName) {
		SecurityWebUser webUser = securityWebUserMapper.selectSecurityWebUserById(Long.valueOf(optId));
		if(Objects.nonNull(webUser)){
			webUser.setAccountnonlocked(Integer.valueOf(optName));
			securityWebUserMapper.updateSecurityWebUser(webUser);
		}else{
			throw new ValidateException("商家信息在系统中不存在");
		}
	}

	/**
	 *  把微信小程序用户升级为加盟商
	 * @Date 2022/10/20 15:54
	 * @author ZhanCheng.Li
	 * @param userId
	 * @param shopName
	 */
	@Override
	public void upgradeDistributor(String userId, String shopName) {
		SecurityWebUser member = securityWebUserMapper.selectSecurityWebUserById(Long.valueOf(userId));
		if(Objects.nonNull(member)
				&& NumberUtil.compare(member.getRoleId(),3L)==0){
			Distributor distributor = new Distributor();
			distributor.setBalance(0.00d);
			distributor.setUserId(member.getId());
			distributor.setAccountstatus(1);
			distributor.setCreateTime(new Date());
			distributor.setShopname(shopName);
			distributorService.insertDistributor(distributor);
			member.setDistributorId(distributor.getId());

			if(StrUtil.isEmpty(member.getNickname())){
				member.setNickname(shopName);
			}
			if(StrUtil.isEmpty(member.getRealname())){
				member.setRealname(shopName);
			}
			if(StrUtil.isEmpty(member.getShopname())){
				member.setShopname(shopName);
			}
			securityWebUserMapper.updateSecurityWebUser(member);
		}
	}

	@Override
	public SecurityWebUser selectMicroUserById(Long id) {
		return securityWebUserMapper.selectSecurityWebUserById(id);
	}

	@Override
	public List<SecurityWebUser> selectMicroUserPage(SecurityWebUser securityWebUser) {
		return securityWebUserMapper.selectMicroUserPage(securityWebUser);
	}

	@Override
	public SecurityWebUser selectMerchantWithPersonalInfo(Long id) {
		SecurityWebUser merchant = securityWebUserMapper.selectSecurityWebUserById(id);
		if(Objects.nonNull(merchant) && NumberUtil.compare(merchant.getRoleId(),4)==0
				&& NumberUtil.compare(merchant.getMerchantpersonalinfoId(),0) !=0){
			MallMerchantPersonalInfo personalInfo = personalInfoService.selectMallMerchantPersonalInfoById(merchant.getMerchantpersonalinfoId());
			if(Objects.nonNull(personalInfo)){
				merchant.setPersonalInfo(personalInfo);
				merchant.setGroupType(personalInfo.getGrouptype());
			}
		}
		return merchant;
	}

	/**
	 *  若依系统创建用户时自动创建拖拖部落系统商家用户
	 * 	兼容两个系统使用
	 * @Date 2022/10/28 16:59
	 * @author ZhanCheng.Li
	 * @param user
	 */
	@Override
	public void autoCreateSecurityWebUser(SysUser user) {
		Long[] roleIds = user.getRoleIds();
		List<SysRole> roleList = roleService.selectRoleAll();
		Map<Long,SysRole> sysRoleMap = roleList.stream().collect(Collectors.toMap(SysRole::getRoleId,a->a,(k1,k2)->k1));
		for(Long roleId : roleIds){
			SysRole role = sysRoleMap.get(roleId);
			if(role.getRoleKey().equals(UserType.COMMON_MERCHANT)){
				if(Objects.nonNull(user.getPhonenumber())){
					SecurityWebUser queryDto = new SecurityWebUser();
					queryDto.setMobile(user.getPhonenumber());
					queryDto.setRoleId(4L);
					List<SecurityWebUser> userList = securityWebUserMapper.selectSecurityWebUserList(queryDto);
					//创建基本不会使用到的用户信息
					if(CollectionUtil.isEmpty(userList)){
						createNeverUseWebUser(user);
					}
				}
			}
		}
	}

	/**
	 *  自动创建的用户，以后基本不会使用，芝士为兼容两个系统数据
	 * @Date 2022/10/28 16:59
	 * @author ZhanCheng.Li
	 * @param user
	 */
	private void createNeverUseWebUser(SysUser user) {
		SecurityWebUser securityWebUser = new SecurityWebUser();
		securityWebUser.setMobile(user.getPhonenumber());
		securityWebUser.setUsername(user.getPhonenumber());
		securityWebUser.setNickname(user.getNickName());
		securityWebUser.setRealname(user.getNickName());
		securityWebUser.setShopname(user.getNickName());
		securityWebUser.setAccountnonlocked(1);
		String userNo = IdUtil.simpleUUID();
		securityWebUser.setUserno(userNo);
		securityWebUser.setRoleId(4L);
		securityWebUser.setCreateTime(new Date());
		securityWebUser.setCreatetime(new Date());
		securityWebUser.setMerchantentertime(new Date());
		securityWebUser.setRealname(securityWebUser.getRealname());
		securityWebUser.setMerchantcheckstatus(1L);
		securityWebUser.setGoodsnumber(0L);
		securityWebUser.setTotalorderamount(0L);
		securityWebUser.setTotalordernumber(0L);
		securityWebUser.setSex(0L);
		securityWebUser.setSelfsupport(0L);
		securityWebUser.setFirstlogin(0);
		securityWebUser.setMerchantinvoicetitletype(0L);
		securityWebUser.setLivebalance(0.00d);
		securityWebUser.setLivetype(0L);
		securityWebUser.setLivestatus(0);
		securityWebUser.setBalance(0.00d);
		securityWebUser.setOrdermessagenumber(0L);
		securityWebUser.setSystemmessagenumber(0L);
		securityWebUser.setWithdrawmessagenumber(0L);
		//设置商家用户身份为个人
		securityWebUser.setMaintype(3L);
		MallMerchantPersonalInfo mallMerchantPersonalInfo = new MallMerchantPersonalInfo();
		mallMerchantPersonalInfo.setCookername(securityWebUser.getRealname());
		personalInfoService.insertMallMerchantPersonalInfo(mallMerchantPersonalInfo);
		securityWebUser.setMerchantpersonalinfoId(mallMerchantPersonalInfo.getId());
		//设置默认评分都为5分
		securityWebUser.setTasteratestar(RandomUtil.randomDouble(3.0d,5.0d,2, RoundingMode.DOWN));
		securityWebUser.setLookratestar(RandomUtil.randomDouble(3.0d,5.0d,2, RoundingMode.DOWN));
		securityWebUser.setAttituderatestar(RandomUtil.randomDouble(3.0d,5.0d,2, RoundingMode.DOWN));
		securityWebUser.setRatestar(RandomUtil.randomDouble(3.0d,5.0d,2, RoundingMode.DOWN));
		securityWebUser.setCompletenum(RandomUtil.randomInt(10));
		securityWebUserMapper.insertSecurityWebUser(securityWebUser);
	}

}
